import { DirectiveBinding } from 'vue';
interface ElType extends HTMLElement {
	_remaining: number;
	_timerCallback: Function;
}
const timerManager: any = {
	callbacks: new Set(),
	interval: null,
	add(callback: Function) {
		this.callbacks.add(callback);
		if (this.callbacks.size === 1) this.start();
	},
	remove(callback: Function) {
		this.callbacks.delete(callback);
		if (this.callbacks.size === 0) this.stop();
	},
	start() {
		this.interval = setInterval(() => {
			this.callbacks.forEach((cb: Function) => cb());
		}, 1000);
	},
	stop() {
		clearInterval(this.interval);
		this.interval = null;
	},
};
// 更新元素显示
function updateDisplay(el: ElType) {
	if (el._remaining > 0) {
		el.textContent = `还剩 ${el._remaining} 秒`;
		el._remaining--;
	} else {
		el.textContent = '时间到！';
	}
}
export default {
	mounted(el: ElType, binding: DirectiveBinding) {
		el._remaining = binding.value;

		updateDisplay(el);

		el._timerCallback = () => {
			updateDisplay(el);
		};

		timerManager.add(el._timerCallback);
	},
	unmounted(el: ElType) {
		// 清理
		timerManager.remove(el._timerCallback);
	},
};
